package cn.stronglink.asset.module.common.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.socket.TextMessage;

import com.baomidou.mybatisplus.toolkit.IdWorker;

import cn.stronglink.asset.message.websocket.MessageHandler;
import cn.stronglink.asset.model.SysOperateLog;
import cn.stronglink.asset.model.User;
import cn.stronglink.asset.module.sys.log.service.SysLogService;
import cn.stronglink.asset.module.sys.user.service.UserService;
import cn.stronglink.suite.core.Constants;
import cn.stronglink.suite.core.base.AbstractController;
import cn.stronglink.suite.core.config.Resources;
import cn.stronglink.suite.core.exception.LoginException;
import cn.stronglink.suite.core.support.Assert;
import cn.stronglink.suite.core.support.login.LoginHelper;
import cn.stronglink.suite.core.util.MD5Encrypt;
import cn.stronglink.suite.core.util.WebUtil;

@Controller
@RequestMapping(value = "")
public class CommonController extends AbstractController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private SysLogService sysLogService;	
	@Autowired
	private MessageHandler messageHandler;
	/**
	 * 登录
	 * @param modelMap
	 * @param request
	 * @param response
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "login")
	public ResponseEntity<ModelMap> login(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response,@RequestBody Map<String, Object> params) {
		Assert.notNull(params.get("account"), "ACCOUNT");
		Assert.notNull(params.get("password"), "PASSWORD");
		
		if (LoginHelper.login(params.get("account").toString(), MD5Encrypt.encrypt(params.get("password").toString()))) {		
			List<String> permissions = userService.getSysPermissionByUsername(params.get("account").toString());
			modelMap.put("permissions", permissions);
			User u =userService.getUserByAccount(params.get("account").toString());
			SysOperateLog log = new SysOperateLog();
			log.setArgs("login[参数1，类型：LoginParam，值：{getUsername : " + params.get("account") 
			+ ",getPassword : " + MD5Encrypt.encrypt(params.get("password").toString())+ "}]");
			log.setId(IdWorker.getId());
			log.setUserName(params.get("account").toString());
			log.setModule("登录");
			log.setOperateTime(new Date());
			log.setOperateType("LOGIN");
			log.setDescription("登录系统");
			log.setIp(WebUtil.getHost(request));
			log.setActName(u.getName());
			//System.out.println(MD5Encrypt.encrypt("123456"));
			sysLogService.insertOperateLog(log);
			
			return setSuccessModelMap(modelMap,SecurityUtils.getSubject().getSession().getAttribute(Constants.CURRENT_USER_NAME).toString());
		}
		throw new LoginException(Resources.getMessage("LOGIN_FAIL"));
		
	}
	
	@RequestMapping(value = "logout")
	public ResponseEntity<ModelMap> logout(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response) {
		Subject currentUser = SecurityUtils.getSubject(); 
		currentUser.logout();
		return setSuccessModelMap(modelMap);	
	}
	
	@RequestMapping(value = "enterAuth")
	public ResponseEntity<ModelMap> enterAuth(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		if(WebUtil.getCurrentUser() != null) {
			return setSuccessModelMap(modelMap);
		}else {
			response.setStatus(401);
			response.getWriter().write("");
			return null;
		}
	}
	
	@RequestMapping(value = "test")
	public ResponseEntity<ModelMap> test(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response) {
		//messageHandler.sendMessageToAllUsers(new TextMessage("{\"notExistCodes\": [],\"existCodes\": [\"9920120313\"],\"roomCode\": \"room_yancao\",\"rackCode\": \"H09\"}"));
		messageHandler.sendMessageToAllUsers(new TextMessage("{\"notExistCodes\": [\"12345678\"],  \"existCodes\": [\"712\", \"713\",\"714\",\"715\"],\"roomCode\": \"2142\",\"rackCode\": \"909571\"}"));           
		return null;
	}
	
}
